<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库" prop="name">
        <el-select v-model="depotIds" multiple placeholder="请选择仓库">
           <el-option
             v-for="item in depotAllList"
             :key="item.id"
             :label="item.name"
             :value="item.id">
           </el-option>
         </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="categoryId" >
          <treeselect v-model="queryParams.categoryId"  style="width: 13.25rem;"    :options="materialcategoryOptions"  @keyup.enter.native="handleQuery" :show-count="true" placeholder="请选择类别" />
      <!--  <el-input v-model="queryParams.categoryId" placeholder="请输入产品类型id" clearable size="small"
          @keyup.enter.native="handleQuery" /> -->
      </el-form-item>
      <el-form-item label="条码" prop="materialParam">
        <el-input v-model="queryParams.materialParam" placeholder="条码/名称/规格/型号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
       <el-form-item label="零库存" prop="barCode">
       <el-select v-model="queryParams.zeroStock"  placeholder="请选择">
          <el-option label="隐藏" value="0" >
             </el-option>
          <el-option label="显示" value="1">
          </el-option>
        </el-select>
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" style="margin-left: 0.55rem;">
       <span><strong>总库存：</strong>{{currentStock}}</span>
      </el-col>
   <el-col :span="1.5" style="margin-left: 6.25rem;">
    <span><strong>总库存金额：</strong>{{currentStockPrice}}</span>
   </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" max-height="630px" :data="materialunitList" @selection-change="handleSelectionChange"
    :summary-method="getSummaries"
       show-summary
    >
      <el-table-column type="selection" width="65" align="center" />
      <el-table-column label="条码" align="center" prop="mBarCode" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="规格" align="center" prop="standard" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="颜色" align="center" prop="color" />
      <el-table-column label="类别" align="center" prop="categoryName" />
      <el-table-column label="单位" align="center" prop="unitName" />
      <el-table-column label="单价" align="center" prop="purchaseDecimal" />
      <el-table-column label="初始库存" align="center" prop="initialStock" />
      <el-table-column label="库存" align="center" prop="currentStock" />
      <el-table-column label="库存金额" align="center" prop="currentStockPrice" />
      <!-- <el-table-column label="meId" align="center" prop="meId" /> -->
      <el-table-column label="库存流水" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="dofindDetailByTypeAndMaterialId(scope.row.meId)"

          >流水</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10, 50, 100, 200,500, 1000,2000]"
      @pagination="getList"
    />

<el-dialog title="查看商品库存流水（全部仓库）" :visible.sync="liushuiVisible" width="1200px" style="min-height: 400px;">
    <el-form :model="queryLiushuiParams" ref="queryLiushuiForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="billNo">
        <el-input v-model="queryLiushuiParams.billNo" placeholder="请输入单据编号" clearable size="small"   @keyup.enter.native="handleQueryLiushui"/>
      </el-form-item>
      <el-form-item label="类型" prop="type" >
        <el-select v-model="queryLiushuiParams.type" style="width: 180px;" clearable>
          <el-option key="销售出库" label="销售出库" value="出库@销售"></el-option>
          <el-option key="采购入库" label="采购入库" value="入库@采购"></el-option>
          <el-option key="其它入库" label="其它入库" value="入库@其它"></el-option>
          <el-option key="其它出库" label="其它出库" value="出库@其它"></el-option>
          <el-option key="报损" label="报损" value="出库@报损"></el-option>
          <el-option key="报溢" label="报溢" value="入库@报溢"></el-option>
        </el-select>
        <!-- <el-input v-model="queryLiushuiParams.type" placeholder="请输入单据编号" clearable size="small"   @keyup.enter.native="handleQueryLiushui"/> -->
      </el-form-item>
      <el-form-item label="单据日期" prop="operTimeRange">
      <el-date-picker size="small"
            v-model="queryLiushuiParams.operTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期" style="width: 330px;">
          </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryLiushui">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQueryLiushui">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="liushuiList"  style="min-height: 400px;"
        >
          <el-table-column type="selection" width="65" align="center" />
          <el-table-column label="单据编号" align="center" prop="number" >
            <template slot-scope="scope">
            <el-link type="primary" @click="myHandleDetail(scope.row)">{{scope.row.number}}</el-link>
              </template>
              </el-table-column>
          <el-table-column label="类型" align="center" prop="type"  width="80"/>
          <el-table-column label="条码" align="center" prop="barCode"  width="100"/>
          <el-table-column label="名称" align="center" prop="materialName" />
          <el-table-column label="仓库名称" align="center" prop="depotName"  width="80"/>
          <el-table-column label="数量" align="center" prop="basicNumber"  width="100"/>
          <el-table-column label="单位" align="center" prop="materialUnit" width="80"/>
          <el-table-column label="日期" align="center" prop="operTime" />
        </el-table>
        <pagination
          v-show="liushuitotal>0"
          :total="liushuitotal"
          :page.sync="queryLiushuiParams.pageNum"
          :limit.sync="queryLiushuiParams.pageSize"
          @pagination="findDetailByTypeAndMaterialId()"
        />
  </el-dialog>
   <bill-detail ref="billDetail"></bill-detail>
    <financial-detail ref="financialDetail"></financial-detail>
  </div>

</template>

<script>
  import { findDetailByTypeAndMaterialId } from "@/api/bill/retail";
  import FinancialDetail from '../comm/dialog/FinancialDetail'
  import BillDetail from '../comm/dialog/BillDetail'
  import { findBillDetailByNumber } from "@/api/bill/retail";
  import { listMaterialunit, getMaterialunit, delMaterialunit, addMaterialunit, updateMaterialunit } from "@/api/material/materialunit";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { materialcategorytreeselect } from "@/api/material/materialcategory";
  import { listDepotByCurrentUserAll } from "@/api/basicsystem/depot";
  import { getListWithStock } from "@/api/material/material";
  import * as math from 'mathjs'
  export default {
  name: "materialstock",
   components: { Treeselect,
    BillDetail,FinancialDetail },
  data() {
    return {
      liushuiVisible:false,//流水
liushuiList:[],//流水集合
liushuitotal:0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 计量单位表格数据
      materialunitList: [],
      depotAllList:[],//仓库
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      depotIds:[],//被选中仓库ID
       // 查询流水参数
      queryLiushuiParams:{
        pageNum: 1,
        pageSize: 10,
        materialId:null,
        billNo:null,
        type:null,
        beginOperTime:null,
        endOperTime:null,
        operTimeRange:[],
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zeroStock:"0",
        materialParam:'',
      depotIds:null//被选中仓库ID
      },
      currentStock:"",//总库存
      currentStockPrice:"",//总库存金额
      materialcategoryOptions:[],//类别
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        basicUnit: [
          { required: true, message: "基本单位不能为空", trigger: "blur" }
        ],
      }
    };
  },
  watch: {
    'queryLiushuiParams.operTimeRange':function(newValue, oldValue) {
      console.log(newValue)
      if(newValue !=null && newValue.length>0){

         this.queryLiushuiParams.beginOperTime = this.parseTime(newValue[0],'{y}-{m}-{d} {h}:{i}:{s}');
         this.queryLiushuiParams.endOperTime =this.parseTime(newValue[1],'{y}-{m}-{d} {h}:{i}:{s}');
      }else{
         this.queryLiushuiParams.beginOperTime = null;
         this.queryLiushuiParams.endOperTime = null;
      }
    }
  },
  created() {
     this.materialcategorytreeselect();
     this.listAllDepot();
    this.getList();
  },
  methods: {
    handleQueryLiushui(){
      this.findDetailByTypeAndMaterialId();
    },
    resetQueryLiushui(){
      // this.queryLiushuiParams.billNo =null;
      // this.resetForm("queryLiushuiForm");
     this.queryLiushuiParams.billNo =null;
     this.queryLiushuiParams.type =null;
     this.queryLiushuiParams.operTimeRange =[];
     this.queryLiushuiParams.beginOperTime =null;
     this.queryLiushuiParams.endOperTime =null
      this.findDetailByTypeAndMaterialId();
    },
    //根据单据查询详情
    myHandleDetail(row){
        let that = this
        //this.toFromType = row.fromType;
           let queryParm={ number: row.number }
           findBillDetailByNumber(queryParm).then(response => {
             //this.liushuiList = response.data;
             that.$refs.billDetail.show(response.data,row.type);
             that.$refs.billDetail.title="详情";

           });
    },
    //根据Id查询流水
    dofindDetailByTypeAndMaterialId(materialId){
console.log(materialId)
this.liushuiVisible=true;
   this.queryLiushuiParams.materialId=materialId;
this.findDetailByTypeAndMaterialId();
    },
    findDetailByTypeAndMaterialId(){
      console.log(this.queryLiushuiParams)
       findDetailByTypeAndMaterialId(this.queryLiushuiParams).then(response => {
         this.liushuiList = response.data.rows;
         console.log( this.liushuiList )
         this.liushuitotal = response.data.total;
       });
    },
    getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
              if (index === 0) {
                sums[index] = '合计';
                return;
              }
              if (index === 1) {
                sums[index] = '-';
                return;
              }
              if (index === 2) {
                sums[index] = '-';
                return;
              }
              if (index === 3) {
                sums[index] = '-';
                return;
              }
              if (index === 4) {
                sums[index] = '-';
                return;
              }
              if (index === 5) {
                sums[index] = '-';
                return;
              }
              if (index === 6) {
                sums[index] = '-';
                return;
              }
              if (index === 7) {
                sums[index] = '-';
                return;
              }
              if (index === 8) {
                sums[index] = '-';
                return;
              }
              if (index === 12) {
                sums[index] = '';
                return;
              }
              const values = data.map(item => Number(item[column.property]));
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                      return math.add(math.bignumber(prev),math.bignumber(curr));
                  } else {
                      return math.bignumber(prev);
                  }
                }, 0);
                sums[index] += '';//可以写单位
              } else {
                sums[index] = 'N/A';
              }
            });

            return sums;
          },
    /** 查询所产仓库 */
    listAllDepot() {


      listDepotByCurrentUserAll(this.queryParams).then(response => {
       /* this.materialList = response.rows;
        this.total = response.total;
        this.loading = false; */
         this.depotAllList=response.list;

      });
    },
    /** 查询类型下拉树结构 */
    materialcategorytreeselect() {
      materialcategorytreeselect().then(response => {
        this.materialcategoryOptions = response.data;
        console.log( this.materialcategoryOptions)
      });
    },
    /** 查询库存列表 */
    getList() {
      this.loading = true;
     this.queryParams.depotIds=this.depotIds.join(",");
      console.log(this.queryParams.depotIds)
      getListWithStock(this.queryParams).then(response => {
        this.materialunitList = response.data.rows;
        this.total = response.data.total;
        this.currentStock= response.currentStock;
         this.currentStockPrice= response.currentStockPrice;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMaterialunit(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改计量单位";
      });
    },

    /** 导出按钮操作 */
    handleExport() {
     this.queryParams.depotIds=this.depotIds.join(",");
     this.download('material/material/stockExport', {
        ...this.queryParams
       }, `库存查询_${this.parseTime(new Date(),'{y}-{m}-{d}')}.xlsx`)
    }
  }
};
</script>
